package com.hnx.admin.utils;

import com.hnx.admin.api.service.cache.CacheAPI;
import com.hnx.admin.json.RegionEntity;
import com.hnx.admin.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;

/*
项目名称： core
创 建 人: 倔强的头发
创建日期： 2025/6/9   15:19:19 
描   述：
*/
@Slf4j
public class AddressUtil implements CacheAPI {
    private static final String UNKNOWN = "unknown";
    private static final String IP_API_URL = "http://ip-api.com/json/%s?fields=status,message,country,regionName,city";
    private static final Pattern IP_PATTERN = Pattern.compile(
            "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$|^" + // IPv4
                    "([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$" + // IPv6
                    "(?:^|\\.)"); // 处理CIDR后缀（如/32）
    // 私有IP地址范围正则
    private static final Pattern PRIVATE_IP_PATTERN = Pattern.compile(
            "(^127\\.\\d+\\.\\d+\\.\\d+$)|" + // 本地回环
                    "(^10\\.\\d+\\.\\d+\\.\\d+$)|" +  // 私有A类
                    "(^172\\.1[6-9]\\.\\d+\\.\\d+$)|" +
                    "(^172\\.2[0-9]\\.\\d+\\.\\d+$)|" +
                    "(^172\\.3[0-1]\\.\\d+\\.\\d+$)|" + // 私有B类
                    "(^192\\.168\\.\\d+\\.\\d+$)"     // 私有C类
    );
public static RegionEntity getLocationByIp(String ip) {
    RedisCache redisCache = SpringUtil.getBean(RedisCache.class);
    RegionEntity region = redisCache.getCacheObject(SYS_IP_LOCATION+ip,RegionEntity.class);
    if(Objects.isNull(region)) {
        RestTemplate restTemplate = new RestTemplate();
        String url = String.format(IP_API_URL, ip);

        try {
            Map<String, String> response = restTemplate.getForObject(url, Map.class);
            if ("success".equals(response.get("status"))) {
                region.setCity(response.get("country"));
                region.setProvince(response.get("regionName"));
                region.setCity(response.get("city"));
            }
        } catch (Exception e) {
//            map.put("country", UNKNOWN);
//            map.put("province", UNKNOWN);
//            map.put("city", UNKNOWN);
            log.error("根据IP地址转换地址失败：" + e.getMessage());
        }
        redisCache.setCacheObject(SYS_IP_LOCATION+ip,region);
    }


    return region;
}
//    public static Map<String, String> parseAddress(String ip) throws Exception {
//        InetAddress ipAddress = InetAddress.getByName(ip);
//        Map<String, String> map = new HashMap<>();
//        try {
//            CityResponse response = cityDatabaseReader.city(ipAddress);
//            String country = response.getCountry().getName();
//            String province = response.getMostSpecificSubdivision().getName();
//            String city = response.getCity().getName();
//            map.put("country", country);
//            map.put("province", province);
//            map.put("city", city);
//        } catch (Exception e) {
//            map.put("country", UNKNOWN);
//            map.put("province", UNKNOWN);
//            map.put("city", UNKNOWN);
//            log.error("根据IP地址转换地址失败：" + e.getMessage());
//        }
//        return map;
//    }
    public static boolean isValidPublicIp(String ip) {
        if (ip == null || ip.isEmpty()) return false;

        // 验证IP格式
        if (!IP_PATTERN.matcher(ip).matches()) return false;

        try {
            // 验证是否为可路由的公网IP
            InetAddress inetAddress = InetAddress.getByName(ip);
            if (inetAddress.isAnyLocalAddress() || inetAddress.isLoopbackAddress()) {
                return false;
            }
            return !PRIVATE_IP_PATTERN.matcher(ip).matches();
        } catch (UnknownHostException e) {
            return false;
        }
    }
}
